﻿using Minecraft.BLL.mysql;
using Minecraft.CacheRedis;
using Minecraft.Config;
using Minecraft.Config.ipConst;
using Minecraft.Model;
using Minecraft.Model.ReqResp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Minecraft.ServerHall
{
	public static class MinecraftSessionExt
	{
		public static void Send<T, U>(this MinecraftSession session,
			EnumCommand command, T req, U resp)
			where T : BaseReq
			where U : BaseResp
		{
			if (JsonConfig.Value.IsConsoleWrite)
			{
				if (command != EnumCommand.Heart_HeartData)
				{
					Console.WriteLine($"发送到客户端的协议为 {command.ToString()}");
				}
			}
			string protocolStr = ProtocolHelper.GetProtocolStr(command);
			string sendStr = $"{protocolStr}{SeparatorConfig.Transfer}{resp.JsonSerialize()}";
			session.Send(sendStr);
			ThreadPool.QueueUserWorkItem(o =>
			{
				var t = o as BaseResp;
				if (t != null)
				{
					switch (t.RespLevel)
					{
						case RespLevelEnum.Warn:
							{
								//记录玩家Id，命令，参数，警告信息
								StringBuilder stringBuilder = new StringBuilder();
								stringBuilder.AppendLine($"    ");
								stringBuilder.AppendLine($"    玩家Id：{session.minecraftSessionInfo.player.PlayerId}{IpConstConfig.GetIpUserNameTipStr(session.RemoteEndPoint.Address.ToString())}");
								stringBuilder.AppendLine($"    发送到客户端的命令：{command.ToString()}");
								stringBuilder.AppendLine($"    时间：{DateTimeOffset.Now.ToStr()}");
								stringBuilder.AppendLine($"    参数：{req.JsonSerialize()}");
								stringBuilder.AppendLine($"    警告信息：{t.Msg}");
								session.Logger.Warn(stringBuilder.ToString());
							}
							break;
						case RespLevelEnum.Error:
							{
								//记录玩家Id，命令，参数，错误信息
								StringBuilder stringBuilder = new StringBuilder();
								stringBuilder.AppendLine($"    ");
								stringBuilder.AppendLine($"    玩家Id：{session.minecraftSessionInfo.player.PlayerId}{IpConstConfig.GetIpUserNameTipStr(session.RemoteEndPoint.Address.ToString())}");
								stringBuilder.AppendLine($"    发送到客户端的命令：{command.ToString()}");
								stringBuilder.AppendLine($"    时间：{DateTimeOffset.Now.ToStr()}");
								stringBuilder.AppendLine($"    参数：{req.JsonSerialize()}");
								stringBuilder.AppendLine($"    错误信息：{t.Msg}");
								session.Logger.Error(stringBuilder.ToString());
							}
							break;
						case RespLevelEnum.Success:
							{

							}
							break;
						default:
							break;
					}
				}
			}, resp);
		}

		/// <summary>
		/// 控制台输出
		/// </summary>
		/// <param name="session"></param>
		/// <returns></returns>
		public static string GetOutputStr(this MinecraftSession session, EnumCommand command)
		{
			string ipUserNameTipStr = IpConstConfig.GetIpUserNameTipStr(session.RemoteEndPoint.Address.ToString());

			string ipAddrStr = $"IP地址：{session.RemoteEndPoint}{ipUserNameTipStr}";
			string playerIdStr = $"玩家Id：{session.minecraftSessionInfo.player.PlayerId}";
			string timeStr = $"时间：{ DateTimeOffset.Now.ToStr()}";
			string onlineNum = $"当前在线人数：{session.AppServer.SessionCount}";
			string protocolStr = $"协议：{command.ToString()}";
			return string.Join("   ", ipAddrStr, playerIdStr, timeStr, onlineNum, protocolStr);
		}

		public static void SaveData(this MinecraftSession session2)
		{
			if (session2.minecraftSessionInfo.IsLogin)
			{
				session2.minecraftSessionInfo.IsLoginAfterThreadRunning = false;
				session2.minecraftSessionInfo.player.LastLogoutTime = DateTimeOffset.Now; //记录最近一次的退出时间
				if (JsonConfig.Value.IsSaveDataLogout)
				{
					ThreadPool.QueueUserWorkItem(o =>
					{
						try
						{
							var session = o as MinecraftSession;
							//更新玩家信息
							PlayerbasisBLL.Update(session.minecraftSessionInfo.player, true);
							//更新物品信息
							GoodsBLL.BatchUpdateWithTablePrefix(session.minecraftSessionInfo.goodsList, MemorySystemManager.goodsTableNameCacheList, session.minecraftSessionInfo.player.PlayerId, true);
							//更新家具信息
							FurnitureBLL.BatchUpdate(session.GetAllFurnitureConvergeList(), session.minecraftSessionInfo.player.PlayerId, true);
							//更新地图信息
							MapBLL.Update(session.minecraftSessionInfo.map, true);
							//更新蓝图信息
							BlueprintBLL.Update(session.minecraftSessionInfo.blueprint, true);
							//更新幸存者列表信息
							SurvivorBLL.BatchUpdate(session.minecraftSessionInfo.survivorList, session.minecraftSessionInfo.player.PlayerId, true);
							//更新尸潮信息
							ZombiesbrushBLL.Update(session.minecraftSessionInfo.zombiesbrushInfo, true);
							//更新用户的成就信息
							//AchievementBLL.BatchUpdate(session.minecraftSessionInfo.playerAchievementList, session.minecraftSessionInfo.player.PlayerId, true);
						}
						catch (Exception ex)
						{
							session2.AppServer.Logger.Fatal($"程序重大异常：最有可能的原因是：代码model与数据库字段不同步，{ex.ToString()}");
						}

					}, session2.DeepCopy());
				}
				else
				{
					RedisCacheHelper redisCacheHelper = new RedisCacheHelper();
					redisCacheHelper.FlushAll();
				}
			}
		}
	}
}
